<template>
    <div id="bracelet">
        <el-breadcrumb class="common-bread">
            <el-breadcrumb-item>手环管理</el-breadcrumb-item>
        </el-breadcrumb>

        <div class="select">
            <label class="label">手环状态：</label>
            <el-select v-model="state">
                <el-option label='全部' value='-1'></el-option>
                <el-option label='未使用' value='0'></el-option>
                <el-option label='使用中' value='1'></el-option>
                <el-option label='维修中' value='3'></el-option>
                <el-option label='已报废' value='4'></el-option>
            </el-select>

            <label class="label">使用学校：</label>
            <el-autocomplete v-model="schoolName" :fetch-suggestions="querySearch" placeholder="请输入使用学校" @select="handleSelect"
                clearable @clear="changeSchool()"></el-autocomplete>
            <label class="label">使用年级：</label>
            <el-select v-model="grade" @change="getClasses()" :disabled="disabled1">
                <el-option label='全部' value='-1'></el-option>
                <el-option :label='item.gradeName' :value='item.gradeId' :key='item.gradeId' v-for="item in grades"></el-option>
            </el-select>
            <label class="label">使用班级：</label>
            <el-select v-model="classId" :disabled="disabled2">
                <el-option label='全部' value='-1'></el-option>
                <el-option :label='item.label' :value='item.value' :key='item.value' v-for="item in classes"></el-option>
            </el-select>
            <div class="mt10">
                <label class="label">入库日期：</label>
                <el-date-picker v-model="entryDate" type="daterange" range-separator="至" start-placeholder="开始日期"
                    end-placeholder="结束日期">
                </el-date-picker>
                <label class="label">绑定日期：</label>
                <el-date-picker v-model="bindDate" type="daterange" range-separator="至" start-placeholder="开始日期"
                    end-placeholder="结束日期">
                </el-date-picker>
                <el-button type="primary" @click="getList(1)">搜索</el-button>
            </div>
        </div>

        <div class="contentBox">
            <div>
                <label class="label">使用学生：</label>
                <el-input placeholder="请输入学生姓名或学籍号" v-model="stuKeyWord" class="keywords"></el-input>
                <label class="label">设备号：</label>
                <el-input placeholder="请输入设备号" v-model="deviceNum" class="keywords"></el-input>
                <el-button type="primary" @click="getList(1)">搜索</el-button>
                <!-- <el-button type="primary" @click="" class="fr ml10">批量解绑</el-button> -->
                <!-- <el-button type="primary" @click="exportBaracelet" class="fr ml10">导出手环</el-button> -->
                <el-button type="primary" @click="$router.push('/importBracelet')" class="fr ml10">导入手环</el-button>
                <el-button type="primary" @click="newBracelet()" class="fr">新增手环</el-button>
            </div>

            <div class="list">
                <el-table :data="list" class="mt10">
                    <el-table-column type="index" label="序号">
                    </el-table-column>
                    <el-table-column prop="deviceNum" label="设备号">
                    </el-table-column>
                    <el-table-column prop="inDate" label="入库日期">
                    </el-table-column>
                    <el-table-column prop="bindDate" label="绑定日期">
                    </el-table-column>
                    <el-table-column prop="schoolName" label="使用学校">
                    </el-table-column>
                    <el-table-column prop="className" label="使用班级">
                    </el-table-column>
                    <el-table-column prop="studentName" label="使用学生姓名">
                    </el-table-column>
                    <el-table-column prop="studentNum" label="使用学生学籍号">
                        </el-table-column>
                    <el-table-column prop="bindState" label="手环状态">
                    </el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <i class="el-icon-edit blueIcon" @click="newBracelet(scope.row)" title="编辑"></i>
                            <i class="el-icon-delete redIcon" @click="deleteBracelet(scope.row)" v-if="scope.row.bindState=='未使用'"
                                title="删除"></i>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="pagination">
                    <el-pagination v-show="this.totalCount > 10" layout="total,prev, pager, next, jumper" :page-size="10"
                        :current-page="currentPage" :total="totalCount" @current-change="handleCurrentChange">
                    </el-pagination>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    import { mapState, mapActions } from "vuex";

    export default {
        data() {
            return {
                deviceNum: "",
                disabled1: true,
                disabled2: true,
                schoolName: "",
                schoolId: "",
                schoolType: "",
                grade: "-1",
                grades: this.$util.getGrades(),
                classes: [],
                classId: "-1",
                stuKeyWord: "",
                state: "-1",
                entryDate: "",
                bindDate: "",
                schools: [],
                list: [],
                totalCount: 0,
                currentPage: 1
            }
        },
        computed: mapState({ user: state => state.user }),
        mounted() {
            this.getSchools().then(schools => {
                let braceletSelect = this.$util.getStore("braceletSelect");
                let braceletInfo = JSON.parse(this.$util.getStore("braceletInfo"));
                if (braceletSelect == 1 && braceletInfo) {

                    this.deviceNum = braceletInfo.deviceNum;
                    this.schoolId = braceletInfo.schoolId;
                    let schoolType = [];
                    schools.forEach(item => {
                        if (item.schoolId == this.schoolId) {
                            this.disabled1 = false;
                            this.disabled2 = true;
                            if (item.haveHigh) schoolType.push("高中");
                            if (item.haveMiddle) schoolType.push("初中");
                            if (item.havePrimary) schoolType.push("小学");
                            return this.schoolName = item.name;
                        };
                    })

                    if (!schoolType.length) schoolType = ["小学", "初中", "高中"];

                    this.stuKeyWord = braceletInfo.stuKeyWord;
                    this.currentPage = braceletInfo.pageNum;
                    this.state = braceletInfo.state + "";
                    this.grades = this.$util.getGrades(schoolType);
                    this.grade = braceletInfo.grade || "-1";
                    this.getClasses(braceletInfo.classId);
                    this.entryDate = [braceletInfo.inStartDate || "", braceletInfo.inEndDate || ""];
                    this.bindDate = [braceletInfo.bindStartDate || "", braceletInfo.bindEndDate || ""];
                    if (braceletInfo.classIds.length) {
                        this.classId = braceletInfo[0];
                    } else {
                        this.classId = -1 + "";
                    }
                    this.getList(this.currentPage);
                }

                this.$util.removeStore("braceletSelect");
                this.$util.removeStore("braceletInfo");
            });

        },
        methods: {
            //获取班级列表
            getClasses(id) {
                this.disabled2 = false;
                this.$axios.get("/adminapi/v1/tools/classes/list", {
                    params: {
                        grade: this.grade,
                        schoolId: this.schoolId,
                        pageSize: 100,
                        pageNum: 1
                    }
                }).then(response => {
                    if (response.data.error == 10000) {
                        this.classes = [];
                        if (!response.data.data) return;
                        let list = response.data.data.content;

                        list.forEach(item => {
                            let gradeName = this.$util.gradeFormat(item.grade * 1);
                            let className = gradeName + item.number + "班";
                            item.name = item.name ? className + `（${item.name}）` : className;

                            this.classes.push({
                                label: item.name,
                                value: item.classId
                            })
                        })
                        this.classId = id || "-1";

                    }
                })
            },
            getList(pageNum) {
                if (pageNum != this.currentPage) this.currentPage = pageNum;

                let classIds = [];
                if (this.schoolId && this.grade != -1) {
                    if (this.classes.length) classIds = this.classes.map(item => item.value);
                    if (!this.classes.length) classIds = null;
                };
                if (this.grade == -1) classIds = [-1];
                let params = {
                    deviceNum: this.deviceNum,
                    schoolId: this.schoolName ? this.schoolId : "",
                    grade: this.schoolId ? this.grade * 1 : "",
                    classIds: classIds,
                    classId: this.classId,
                    stuKeyWord: this.stuKeyWord.trim(),
                    state: this.state * 1,
                    pageNum: pageNum * 1,
                    pageSize: 10,
                    inStartDate: this.entryDate ? new Date(this.entryDate[0]).getTime() : "",
                    inEndDate: this.entryDate ? new Date(this.entryDate[1]).getTime() : "",
                    bindStartDate: this.bindDate ? new Date(this.bindDate[0]).getTime() : "",
                    bindEndDate: this.bindDate ? new Date(this.bindDate[1]).getTime() : ""
                }
                //保存搜索条件
                this.$util.setStore("braceletInfo", JSON.stringify(params));
                delete params.classId;

                this.$axios.post("/adminapi/bangle/v1/list", params).then(response => {
                    if (response.data.error == 10000) {
                        this.list = [];
                        let list = response.data.data.list;
                        this.totalCount = response.data.data.totalNum;
                        let stateArray = new Map([
                            [0, "未使用"], [1, "使用中"], [2, "已破损"], [3, "维修中"], [4, "已报废"]
                        ])



                        list.forEach(item => {
                            item.bindState = stateArray.get(item.bindState);

                            let className;
                            if (item.grade && item.number) className = item.grade + item.number + "班";
                            item.className = item.className ? className + `（${item.className}）` : className;
                            item.inDate = new Date(item.inDate).format("yyyy-MM-dd");
                            item.bindDate = item.bindDate ? new Date(item.bindDate).format("yyyy-MM-dd") : "";
                            this.list.push(item);
                        });
                    } else {
                        this.$util.errorMsg(response.data.message);
                    }
                }).catch(response => {
                    this.$util.errorMsg(response.data.message);
                })
            },
            deleteBracelet(row) {
                this.$confirm(`您确定要删除手环 “${row.deviceNum}” ？`, "温馨提示", this.$util.confirmBtnText).then(() => {
                    this.$axios.get("/adminapi/bangle/v1/del", { params: { deviceNum: row.deviceNum } }).then(response => {
                        if (response.data.error == 10000) {
                            this.getList(this.currentPage);
                            this.$util.successMsg("删除成功");
                        } else {
                            this.$util.errorMsg(response.data.message);
                        }
                    })
                }).catch(() => { })
            },
            //获取学校列表
            getSchools() {
                return new Promise((resolve) => {
                    this.$util.getSchools().then(schools => {
                        schools.forEach(item => {
                            this.schools.push({
                                value: item.name,
                                schoolId: item.schoolId,
                                haveHigh: item.haveHigh,
                                haveMiddle: item.haveMiddle,
                                havePrimary: item.havePrimary
                            })
                        });
                        resolve(schools);
                    })
                })
            },
            createFilter(queryString) {
                return (school) => {
                    return (school.value.toLowerCase().indexOf(queryString.toLowerCase()) >= 0);
                };
            },
            querySearch(queryString, cb) {
                let schools = this.schools;
                let results = queryString ? schools.filter(this.createFilter(queryString)) : schools;
                // 调用 callback 返回建议列表的数据
                cb(results);
                results = [];
            },
            changeSchool() {
                if (!this.schoolName) {
                    this.schoolId = "";
                    this.disabled1 = true;
                    this.disabled2 = true;
                    this.grade = "-1";
                    this.classId = "-1";
                    return;
                }
            },
            handleSelect(item) {
                this.schoolId = item.schoolId;
                let schoolType = [];
                if (item.haveHigh) schoolType.push("高中");
                if (item.haveMiddle) schoolType.push("初中");
                if (item.havePrimary) schoolType.push("小学");
                this.grade = "-1";
                this.classId = "-1";
                this.disabled1 = false;
                this.disabled2 = true;
                this.grades = this.$util.getGrades(schoolType);
            },
            //导出手环
            exportBaracelet() {
                let classIds = [];
                if (this.schoolId) {
                    if (this.grade != -1 && this.classId == -1) {
                        classIds = this.classes.filter(item => item.value);
                    } else if (this.classId != -1) {
                        classIds = [this.classId];
                    }
                }
                let params = {
                    deviceNum: this.deviceNum,
                    schoolId: this.schoolId,
                    grade: this.grade * 1,
                    classIds: classIds,
                    stuKeyWord: this.stuKeyWord.trim(),
                    state: this.state * 1,
                    inStartDate: this.entryDate ? new Date(this.entryDate[0]).getTime() : "",
                    inEndDate: this.entryDate ? new Date(this.entryDate[1]).getTime() : "",
                    bindStartDate: this.bindDate ? new Date(this.bindDate[0]).getTime() : "",
                    bindEndDate: this.bindDate ? new Date(this.bindDate[1]).getTime() : ""
                }

                this.$axios.post("/adminapi/bangle/v1/export/excel", params).then(response => {
                    if (response.data.error == 10000) location.href = response.data.data;
                })
            },
            handleCurrentChange(val) {
                this.currentPage = val;
                this.getList(val);
            },
            //新增或编辑手环
            newBracelet(row) {
                this.saveSelectHistory();
                if (!row) return this.$router.push('/newBracelet');
                this.$router.push('/newBracelet?id=' + row.deviceNum);
            },
            saveSelectHistory() {
                let classIds = [];
                if (this.schoolId) {
                    if (this.grade != -1 && this.classId == -1) {
                        classIds = this.classes.filter(item => item.value);
                    } else if (this.classId != -1) {
                        classIds = [this.classId];
                    }
                }
                let params = {
                    deviceNum: this.deviceNum,
                    schoolId: this.schoolId,
                    grade: this.schoolId ? this.grade * 1 : "",
                    classIds: classIds,
                    stuKeyWord: this.stuKeyWord.trim(),
                    state: this.state * 1,
                    classId: this.classId,
                    pageNum: this.currentPage * 1,
                    pageSize: 10,
                    inStartDate: this.entryDate ? new Date(this.entryDate[0]).getTime() : "",
                    inEndDate: this.entryDate ? new Date(this.entryDate[1]).getTime() : "",
                    bindStartDate: this.bindDate ? new Date(this.bindDate[0]).getTime() : "",
                    bindEndDate: this.bindDate ? new Date(this.bindDate[1]).getTime() : ""
                }

                this.$util.setStore("braceletInfo", JSON.stringify(params));
            }

        }
    }
</script>
<style>
    #bracelet .label {
        display: inline-block;
        width: 70px;
    }

    .el-autocomplete>.el-input {
        width: 200px;
    }

    .selectBox {
        width: 480px;
        margin: 0 auto;
        padding: 15px 10px;
        background: #fff;
        border: solid 1px #ddd;
    }

    #bracelet .select {
        margin: 0 32px;
        padding: 24px;
        background-color: #fff;
    }

    #bracelet .contentBox {
        height: calc(100% - 265px);
    }
</style>